/*
 * @Date: 2023-04-04 09:39:47
 * @LastEditTime: 2023-06-07 14:08:33
 */
import axios from 'axios'
import { VueAxios } from './axios'
import store from '../store'
import { message } from 'ant-design-vue'
import router from '../router'
import storage from 'store'

// 创建 axios 实例
const service = axios.create({
  // API 请求的默认前缀
  baseURL: '/web',
  timeout: 60000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  message.error('服务器异常')
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use((config) => {
  config.headers.token = store.getters.token
  return config
}, errorHandler)

// response interceptor
service.interceptors.response.use((response) => {
  const errCodes = [401, 403]
  if (errCodes.includes(response.data.code)) {
    message.warning(response.data.msg)
    storage.remove('token')
    router.push({
      path: '/user/login'
    })
  }
  return response.data
}, errorHandler)

const request = {
  get (url, data, config) {
    return request.request('GET', url, { params: data }, config)
  },
  post (url, data, config) {
    return request.request('POST', url, { data }, config)
  },
  put (url, data, config) {
    return request.request('PUT', url, { data }, config)
  },
  delete (url, data, config) {
    return request.request('DELETE', url, { params: data }, config)
  },
  request (method = 'GET', url, data, config) {
    const options = Object.assign({}, config)
    return new Promise((resolve, reject) => {
      service({ method, url, ...data, requestOptions: options })
        .then((res) => {
          resolve(res)
        })
        .catch((e) => {
          reject(e)
        })
    })
  }
}

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export { installer as VueAxios, request as axios }
